//
//  PictureSelectorCollection.swift
//  Sinaweibo
//
//  Created by 谌桃 on 15/12/6.
//  Copyright © 2015年 ryan.chen. All rights reserved.
//

import UIKit
import SnapKit
private let reuseIdentifier = "Cell"
private let pictureCellMargin: CGFloat = 10
private let rowCount: CGFloat = 4
private let maximageCount = 3


class PictureSelectorViewController: UICollectionViewController {
    
    
    //声明图片数组 数据源
    lazy var imageList = [UIImage]()
    init() {
        let w = (width - (rowCount + 1) * pictureCellMargin) / rowCount
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: w, height: w)
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        super.init(collectionViewLayout: layout)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Register cell classes
        self.collectionView!.registerClass(PictureSeletorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of item
        let detla = imageList.count == maximageCount ? 0 : 1
        let count = imageList.count + detla
        return count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSeletorCell
        
        cell.backgroundColor = UIColor.randomColor()
        cell.selectorDelegate = self
        if indexPath.item == imageList.count {
            cell.iconImage = nil
        } else {
            cell.iconImage = imageList[indexPath.item]
        }
        return cell
    }
}


//继承了 PictureSeletorDelegate 分类
extension PictureSelectorViewController: PictureSeletorDelegate {
    func userWillChosePicture(cell: PictureSeletorCell) {
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        //设置是否允许编辑
        //        picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell: PictureSeletorCell) {
        //获取点击cell的indexPath!
        let indexPath = collectionView!.indexPathForCell(cell)!
        //删除对应的数据
        imageList.removeAtIndex(indexPath.item)
        //刷新数据
        collectionView?.reloadData()
    }
}

extension PictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //        print(image)
        //        print(editingInfo)
        imageList.append(image)
        
        //刷新视图
        collectionView?.reloadData()
        //一旦实现了图片选择器的协议方法  dismiss操作 需要程序员手动dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }
}


//-------------------------------------------------
@objc protocol PictureSeletorDelegate: NSObjectProtocol {
    //协议方法
    optional func userWillChosePicture(cell: PictureSeletorCell)
    
    //删除图片
    optional func userWillDeletePicture(cell: PictureSeletorCell)
}

class PictureSeletorCell: UICollectionViewCell {
    
    
    var iconImage: UIImage? {
        didSet {
            deleteBtn.hidden = iconImage == nil
            if iconImage == nil {
                addBtn.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
                return
            }
            addBtn.setImage(iconImage, forState: .Normal)
        }
    }
    
    //MARK: 响应方法
    @objc private func addBtnDidClick() {
        selectorDelegate?.userWillChosePicture?(self)
    }
    
    @objc private func deleteBtnDidClick() {
        selectorDelegate?.userWillDeletePicture?(self)
    }
    
    //声明一个若引用的代理
    weak var selectorDelegate: PictureSeletorDelegate?
    //MARK: 重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: 设置UI 及布局
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置布局
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(contentView.snp_right)
            make.top.equalTo(contentView.snp_top)
        }
        
        //添加点击事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        //设置显示样式
        addBtn.imageView?.contentMode = .ScaleAspectFill
        
    }
    
    //MARK: 懒加载所有的子控件
    private lazy var addBtn: UIButton = UIButton(imageName: "compose_pic_add", backImage: nil)
    
    private lazy var deleteBtn: UIButton = UIButton(imageName: "compose_photo_close", backImage: nil)
}
